//
//  KSFeedbackViewController.swift
//  Supermarket
//
//  Created by liuxm on 2017/9/19.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import Photos

class KSFeedbackViewController: KSBaseViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PickerPhotoCompleteDelegate,ChoosePhotoDelegate,ChooseQuestionTypeDelegate {
    
    private var collectionView: UICollectionView!
    private var photo: [PHAsset] = []
    private var camera: [UIImage] = []
    private var imageManager:PHCachingImageManager!
    private let bottomBtn = UIButton()
    private var questionTypeArray: [NSInteger] = []
    private var questionDescibeString = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let bottomHeight: CGFloat = 50
        
        self.title = "帮助反馈"
        self.view.backgroundColor = KSColor.kColorViewBackground
        
        let layout = UICollectionViewFlowLayout()
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 10, width: KSConstants.kScreenWidth, height: KSConstants.kScreenHeight - bottomHeight - 64 - 10), collectionViewLayout: layout)
        self.collectionView.register(KSFeedBackFirstCollectionViewCell.self, forCellWithReuseIdentifier: "KSFeedBackFirstCollectionViewCell")
        self.collectionView.register(KSFeedBackPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "KSFeedBackPhotoCollectionViewCell")
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.backgroundColor = UIColor.white
        self.view.addSubview(collectionView)
        
        self.imageManager = PHCachingImageManager()
        
        
        bottomBtn.isEnabled = false
        bottomBtn.setTitle("提交", for: .normal)
        bottomBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorMainRed), for: .normal)
        bottomBtn.setBackgroundImage(KSTools.createImageWithColor(color: KSColor.kColorButtonDisabled), for: .disabled)
        
        self.view.addSubview(bottomBtn)
        bottomBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(0)
            make.left.right.equalTo(0)
            make.height.equalTo(bottomHeight)
        }
    }
    
    @objc func choosePicture() {
        self.openPhoto()
    }
    
    private func choosePhotoAndCamera() {
        let alertViewController = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        let photoAlert = UIAlertAction.init(title: "相册", style: .default) { (UIAlertAction) in
            self.openPhoto()
        }
        let cameraAlert = UIAlertAction.init(title: "相机", style: .default) { (UIAlertAction) in
            self.openCamera()
        }
        let cancelAlert = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        alertViewController.addAction(photoAlert)
        alertViewController.addAction(cameraAlert)
        alertViewController.addAction(cancelAlert)
        self.present(alertViewController, animated: true) {}
    }
    
    private func openCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.sourceType = UIImagePickerControllerSourceType.camera
            picker.allowsEditing = true
            self.present(picker, animated: true, completion: {
            })
            
        }
    }
    
    private func openPhoto() {
        let vc = KSPickerPhotoAlbumViewController()
        vc.delegate = self
        vc.selectPhotoArray = self.photo
        vc.maxSelected = 9
        vc.cameraChooseNumber = self.camera.count
        let nav = UINavigationController(rootViewController: vc)
        nav.tabBarController?.tabBar.isHidden = true
        self.present(nav, animated: true, completion: nil)
    }
    
    func pickerPhotoComplete(asset: [PHAsset]) {
        self.photo = asset
        collectionView.reloadData()
        self.judgeBtnIsDiable()
    }
    
    func chooseQuestionTypeCallBack(btnTag: [NSInteger], questionDescibe: String) {
        self.questionTypeArray = btnTag
        self.questionDescibeString = questionDescibe
        self.judgeBtnIsDiable()
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        picker.dismiss(animated: true) {
        }
        self.camera.append(image)
        self.collectionView.reloadData()
    }
    
    private func judgeBtnIsDiable() {
        if (self.photo.count > 0) && (self.questionTypeArray.count > 0) && (self.questionDescibeString.characters.count > 0) {
            bottomBtn.isEnabled = true
        } else {
            bottomBtn.isEnabled = false
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension KSFeedbackViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var num = 1
        if section > 0 {
            if (self.photo.count + self.camera.count) == 9 {
                num = 9
            } else {
                num = self.photo.count + 1 + self.camera.count
            }
        }
        return num
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.section == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "KSFeedBackFirstCollectionViewCell", for: indexPath) as! KSFeedBackFirstCollectionViewCell
            cell.delegate = self
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "KSFeedBackPhotoCollectionViewCell", for: indexPath) as! KSFeedBackPhotoCollectionViewCell
            if indexPath.row == 3 || indexPath.row == 7 {
                cell.setBackViewKeepRightConstraint()
            } else {
                cell.setBackViewKeepLeftConstraint()
            }
            
            if self.photo.count > 0 || self.camera.count > 0 {
                if self.photo.count > 0 && self.photo.count > indexPath.row {
                    if self.photo.count == indexPath.row {
                        cell.setChoosePhotoImage()
                    } else {
                        let asset = self.photo[indexPath.row]
                        self.imageManager.requestImage(for: asset, targetSize: CGSize.init(width: 50, height: 50), contentMode: .aspectFit, options: nil) { (image, nfo) in
                            cell.setBtnBackImage(image: image!,row: indexPath.row)
                        }
                    }
                } else {
                    if (self.photo.count + self.camera.count) == indexPath.row {
                        cell.setChoosePhotoImage()
                    } else {
                        print(indexPath.row)
                        cell.setBtnBackImage(image: self.camera[indexPath.row - self.photo.count],row: indexPath.row)
                    }
                }
            } else {
                cell.setChoosePhotoImage()
            }
            
            cell.delegate = self
            return cell
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.section == 0 {
            return CGSize.init(width: KSConstants.kScreenWidth, height: 340)
        } else {
            return CGSize.init(width: KSConstants.kScreenWidth/4, height: KSConstants.kScreenWidth/4)
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func deletePhotoCallBack(row: NSInteger) {
        self.photo.remove(at: row)
        self.collectionView.reloadData()
    }
    
    func choosePhotCallBack() {
        //self.openPhoto()
        self.choosePhotoAndCamera()
    }
}

